import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import {
  Star,
  GitFork,
  TrendingUp,
  ExternalLink,
  RefreshCw,
  AlertCircle,
  Loader2,
  Search,
  Filter,
  Sparkles,
  Settings as SettingsIcon,
} from 'lucide-react';
import { getProviders, callAIStream } from '@/lib/ai-config';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Link } from 'react-router-dom';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

interface Repo {
  rank: number;
  name: string;
  description: string;
  language: string;
  stars: number;
  forks: number;
  stars_today: number;
  url: string;
  contributors: string[];
}

interface Language {
  value: string;
  label: string;
}

/**
 * GitHub Trending 页面
 * 实时爬取并展示 GitHub 热门仓库
 */
export default function GitHubTrending() {
  const [repos, setRepos] = useState<Repo[]>([]);
  const [filteredRepos, setFilteredRepos] = useState<Repo[]>([]);
  const [languages, setLanguages] = useState<Language[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
  const [isCached, setIsCached] = useState(false);
  
  // 筛选和排序状态
  const [selectedLanguage, setSelectedLanguage] = useState<string>('');
  const [selectedSince, setSelectedSince] = useState<string>('daily');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<'rank' | 'stars' | 'stars_today' | 'forks'>('rank');
  
  // AI 总结状态
  const [summary, setSummary] = useState<string>('');
  const [summaryLoading, setSummaryLoading] = useState(false);
  const [summaryError, setSummaryError] = useState<string | null>(null);

  // 加载语言列表
  useEffect(() => {
    fetchLanguages();
  }, []);

  // 加载数据
  useEffect(() => {
    fetchTrending();
  }, [selectedLanguage, selectedSince]);

  // 筛选和排序
  useEffect(() => {
    if (!Array.isArray(repos)) {
      setFilteredRepos([]);
      return;
    }

    let filtered = [...repos];

    // 搜索过滤
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (repo) =>
          repo.name.toLowerCase().includes(query) ||
          repo.description.toLowerCase().includes(query)
      );
    }

    // 排序
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'stars':
          return b.stars - a.stars;
        case 'stars_today':
          return b.stars_today - a.stars_today;
        case 'forks':
          return b.forks - a.forks;
        case 'rank':
        default:
          return a.rank - b.rank;
      }
    });

    setFilteredRepos(filtered);
  }, [repos, searchQuery, sortBy]);

  const fetchLanguages = async () => {
    try {
      const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5001/api';
      const response = await fetch(`${API_BASE}/github/languages`);
      const result = await response.json();
      if (result.success) {
        setLanguages(result.data);
      }
    } catch (err) {
      console.error('获取语言列表失败:', err);
    }
  };

  const fetchTrending = async (forceRefresh: boolean = false) => {
    setLoading(true);
    setError(null);

    try {
      const params = new URLSearchParams({
        since: selectedSince,
        limit: '50',
        force: forceRefresh.toString(),
      });
      
      if (selectedLanguage) {
        params.append('language', selectedLanguage);
      }

      const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5001/api';
      const response = await fetch(
        `${API_BASE}/github/trending?${params}`
      );

      if (!response.ok) {
        throw new Error('API 请求失败');
      }

      const result = await response.json();

      if (result.success) {
        setRepos(result.data);
        setIsCached(result.cached || false);
        setLastUpdate(result.cached_at ? new Date(result.cached_at) : new Date());
      } else {
        throw new Error(result.error || '获取数据失败');
      }
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : '获取数据失败，请确保 Python API 服务已启动 (端口 5001)'
      );
    } finally {
      setLoading(false);
    }
  };

  // 格式化数字
  const formatNumber = (num: number) => {
    if (num >= 1000) {
      return `${(num / 1000).toFixed(1)}k`;
    }
    return num.toString();
  };

  // AI 总结功能
  const handleGenerateSummary = async () => {
    // 检查是否配置了 AI 提供商
    const providers = getProviders();
    const enabledProvider = providers.find(p => p.enabled && p.apiKey);
    
    if (!enabledProvider) {
      setSummaryError('请先在系统设置中配置 AI 提供商');
      return;
    }

    if (filteredRepos.length === 0) {
      setSummaryError('没有可总结的内容');
      return;
    }

    setSummaryLoading(true);
    setSummaryError(null);
    setSummary('');

    try {
      // 准备提示词
      const repoList = filteredRepos.slice(0, 20).map((repo, index) => 
        `${index + 1}. ${repo.name}\n` +
        `   - 描述: ${repo.description || '无描述'}\n` +
        `   - 语言: ${repo.language}\n` +
        `   - 星标: ${repo.stars} (今日+${repo.stars_today})\n` +
        `   - Forks: ${repo.forks}`
      ).join('\n\n');

      const prompt = `请分析以下 GitHub Trending 仓库列表（${selectedSince === 'daily' ? '今日' : selectedSince === 'weekly' ? '本周' : '本月'}热门），提供一份清晰的技术趋势总结：

${repoList}

请按以下格式输出：

## 🎯 主要技术趋势

[从编程语言、框架、技术领域等角度，用2-3个要点总结当前趋势]

## ⭐ 值得关注的项目

[选择3-5个最有价值的项目，每个项目用一行说明，格式如下：]
- **项目名称** - 一句话亮点描述

## 📊 整体趋势分析

[用2-3句话总结整体技术发展方向和社区关注点]

要求：
- 使用中文输出
- 严格按照上述 Markdown 格式
- 每个部分简洁明了，突出重点
- 项目名称使用加粗格式
- 总字数控制在 400 字左右`;

      const messages = [
        {
          id: 'prompt',
          role: 'user' as const,
          content: prompt,
          timestamp: Date.now(),
        },
      ];

      const config = {
        temperature: 0.7,
        maxTokens: 2000,
        topP: 0.9,
        stream: true,
      };

      let fullContent = '';
      
      for await (const chunk of callAIStream(
        enabledProvider,
        enabledProvider.models[0],
        messages,
        config
      )) {
        fullContent += chunk;
        setSummary(fullContent);
      }
    } catch (err) {
      setSummaryError(err instanceof Error ? err.message : '生成总结失败');
    } finally {
      setSummaryLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* 页面标题和操作栏 */}
      <div className="flex flex-col gap-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">GitHub Trending</h1>
            <p className="text-muted-foreground">
              发现今日最热门的开源项目
              {lastUpdate && (
                <span className="ml-2 text-xs">
                  {isCached && '(缓存) '}
                  更新于 {lastUpdate.toLocaleTimeString()}
                </span>
              )}
            </p>
          </div>
          <Button onClick={() => fetchTrending(true)} disabled={loading}>
            <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
            刷新
          </Button>
        </div>

        {/* 筛选工具栏 */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex flex-wrap gap-3">
              {/* 搜索框 */}
              <div className="relative flex-1 min-w-[200px]">
                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  placeholder="搜索仓库..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-9"
                />
              </div>

              {/* 语言筛选 */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" className="min-w-[120px]">
                    <Filter className="mr-2 h-4 w-4" />
                    {languages.find((l) => l.value === selectedLanguage)?.label || '全部语言'}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="max-h-[300px] overflow-y-auto">
                  <DropdownMenuLabel>选择语言</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  {languages.map((lang) => (
                    <DropdownMenuItem
                      key={lang.value}
                      onClick={() => setSelectedLanguage(lang.value)}
                    >
                      {lang.label}
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>

              {/* 时间范围 */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline">
                    {selectedSince === 'daily' && '今日'}
                    {selectedSince === 'weekly' && '本周'}
                    {selectedSince === 'monthly' && '本月'}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel>时间范围</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={() => setSelectedSince('daily')}>
                    今日
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setSelectedSince('weekly')}>
                    本周
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setSelectedSince('monthly')}>
                    本月
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>

              {/* 排序方式 */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline">
                    排序:
                    {sortBy === 'rank' && ' 排名'}
                    {sortBy === 'stars' && ' 星标'}
                    {sortBy === 'stars_today' && ' 今日新增'}
                    {sortBy === 'forks' && ' Fork数'}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel>排序方式</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={() => setSortBy('rank')}>
                    按排名
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setSortBy('stars')}>
                    按星标数
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setSortBy('stars_today')}>
                    按今日新增
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => setSortBy('forks')}>
                    按 Fork 数
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* AI 趋势总结 */}
      {repos.length > 0 && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Sparkles className="h-5 w-5 text-primary" />
                <CardTitle>AI 趋势总结</CardTitle>
              </div>
              <Button 
                onClick={handleGenerateSummary}
                disabled={summaryLoading}
                size="sm"
              >
                {summaryLoading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    生成中...
                  </>
                ) : (
                  <>
                    <Sparkles className="mr-2 h-4 w-4" />
                    生成总结
                  </>
                )}
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {!summary && !summaryError && !summaryLoading && (
              <div className="text-center py-8 text-muted-foreground">
                <Sparkles className="mx-auto h-12 w-12 mb-4 opacity-50" />
                <p className="mb-2">点击上方按钮，让 AI 为你总结当前热门趋势</p>
                <p className="text-xs">
                  基于前 20 个热门仓库生成分析报告
                </p>
              </div>
            )}
            
            {summaryError && (
              <div className="rounded-lg bg-destructive/10 p-4 text-sm">
                <div className="flex items-start gap-3">
                  <AlertCircle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
                  <div className="flex-1">
                    <p className="font-medium text-destructive mb-2">{summaryError}</p>
                    {summaryError.includes('配置') && (
                      <Link to="/app/settings">
                        <Button variant="outline" size="sm" className="gap-2">
                          <SettingsIcon className="h-4 w-4" />
                          前往设置
                        </Button>
                      </Link>
                    )}
                  </div>
                </div>
              </div>
            )}
            
            {summaryLoading && (
              <div className="space-y-2">
                <div className="h-4 bg-muted animate-pulse rounded" />
                <div className="h-4 bg-muted animate-pulse rounded w-5/6" />
                <div className="h-4 bg-muted animate-pulse rounded w-4/6" />
              </div>
            )}
            
            {summary && (
              <div className="prose prose-sm dark:prose-invert max-w-none 
                            prose-headings:text-foreground 
                            prose-h2:text-lg prose-h2:font-bold prose-h2:mt-6 prose-h2:mb-3
                            prose-p:text-muted-foreground prose-p:leading-relaxed prose-p:my-2
                            prose-ul:my-3 prose-li:my-1.5 prose-li:text-muted-foreground
                            prose-strong:text-foreground prose-strong:font-semibold
                            [&>*:first-child]:mt-0">
                <ReactMarkdown remarkPlugins={[remarkGfm]}>
                  {summary}
                </ReactMarkdown>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 加载状态 */}
      {loading && (
        <div className="flex items-center justify-center py-12">
          <div className="text-center">
            <Loader2 className="mx-auto h-8 w-8 animate-spin text-primary" />
            <p className="mt-4 text-muted-foreground">正在爬取数据...</p>
          </div>
        </div>
      )}

      {/* 错误状态 */}
      {error && !loading && (
        <Card className="border-destructive">
          <CardContent className="pt-6">
            <div className="flex items-start gap-3">
              <AlertCircle className="h-5 w-5 text-destructive" />
              <div>
                <p className="font-medium text-destructive">加载失败</p>
                <p className="mt-1 text-sm text-muted-foreground">{error}</p>
                <div className="mt-3 rounded-md bg-muted p-3 text-xs">
                  <p className="font-medium">启动 API 服务:</p>
                  <code className="mt-1 block">
                    cd mytools/api_server && python app.py
                  </code>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 仓库列表 */}
      {!loading && !error && filteredRepos.length > 0 && (
        <div className="space-y-3">
          {filteredRepos.map((repo) => (
            <Card key={repo.rank} className="transition-all hover:shadow-md">
              <CardContent className="pt-6">
                <div className="space-y-3">
                  {/* 标题和排名 */}
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex items-start gap-3 flex-1">
                      <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-sm font-bold text-primary-foreground">
                        {repo.rank}
                      </div>
                      <div className="min-w-0 flex-1">
                        <a
                          href={repo.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-2 text-lg font-semibold hover:text-primary break-all"
                        >
                          {repo.name}
                          <ExternalLink className="h-4 w-4 shrink-0" />
                        </a>
                        {repo.description && (
                          <p className="mt-1 text-sm text-muted-foreground line-clamp-2">
                            {repo.description}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* 统计信息 */}
                  <div className="flex flex-wrap items-center gap-4 text-sm">
                    {repo.language !== 'Unknown' && (
                      <Badge variant="secondary">{repo.language}</Badge>
                    )}
                    <div className="flex items-center gap-1 text-muted-foreground">
                      <Star className="h-4 w-4" />
                      <span>{formatNumber(repo.stars)}</span>
                    </div>
                    <div className="flex items-center gap-1 text-muted-foreground">
                      <GitFork className="h-4 w-4" />
                      <span>{formatNumber(repo.forks)}</span>
                    </div>
                    {repo.stars_today > 0 && (
                      <div className="flex items-center gap-1 text-green-600">
                        <TrendingUp className="h-4 w-4" />
                        <span className="font-medium">+{formatNumber(repo.stars_today)}</span>
                        <span className="text-xs">today</span>
                      </div>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* 无结果 */}
      {!loading && !error && filteredRepos.length === 0 && repos.length > 0 && (
        <Card>
          <CardContent className="py-12 text-center">
            <p className="text-muted-foreground">没有找到匹配的仓库</p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
